package com.organization

import grails.test.*

class DepartmentServiceTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testServiceMethods() {
        //create testing service
        def testService = new DepartmentService()

        //mock commonService methods
        def mockControl = mockFor(CommonService,true)
        mockControl.demand.nodeIdToDbId(3..3) {nodeId->
            nodeId.replaceAll("[a-zA-Z/_]","")
        }
        mockControl.demand.convertDateFromJson(2..2) {date->
            new Date()
        }
        testService.commonService = mockControl.createMock()

        //mock domain for tests
        mockDomain(Department)
        def testDep = new Department(id: 1, name:"Dep1")
        assertNotNull "can't save department",testDep.save()

        //test getDepartmentInfo(String depId)
        def result = testService.getDepartmentInfo("Department_1")
        assertNotNull "null result in getDepartmentInfo",result
        assertEquals "true",result.success
        assertEquals "Dep1",result.name

        //test updateDepartmentInfo(params)
        result = testService.updateDepartmentInfo([nodeId: "Department_1", name: "Dep2"])
        assertNotNull "null result in updateDepartmentInfo",result
        assertNotNull "name field is null",result.newName
        assertNotNull "nodeId field is null",result.nodeId
        assertEquals "true",result.success
        def foundDep = Department.findById(1)
        assertNotNull "found department is null",foundDep
        assertEquals "Dep2",foundDep.name

        //test addDepartment(params)
        result = testService.addDepartment([parentNodeId: "Organization", name: "Dep3"])
        assertNotNull "null result in addDepartment",result
        assertEquals "Organization",result.parentNodeId
        assertNotNull "nodeId field is null",result.nodeId
        assertEquals "true",result.success

        foundDep = Department.findById(2)
        assertNotNull "found department is null",foundDep
        assertEquals "Dep3",foundDep.name
        assertEquals 2,Department.findAll().size()

        //test deleteDepartment(params)
        result = testService.deleteDepartment([nodeId: "Department_1",])
        assertNotNull "null result in deleteDepartment",result
        assertEquals "true",result.success

        foundDep = Department.findById(1)
        assertNull "department was not deleted",foundDep
        assertEquals 1,Department.findAll().size()

        //verify count of mocked methods calls
        mockControl.verify()
    }
}
